﻿Imports System.ComponentModel
Imports System.IO
Imports System.Text
Imports HslCommunication
Imports HslCommunication.Profinet.Siemens

Imports System.Speech.Synthesis '用于生成响应的事件
Imports System.Speech
Imports System.Speech.Recognition
Public Class testForm
    Const a As String = "开始"
    Dim dtTa As DataTable
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim objHWSetting As New clsHWSetting
        Dim szSql As String = ""
        DBacs.BeginTransaction()
        szSql &= "select * from sf.b_prod_pgd_info"
        dtTa = DBacs.ExecuteSql(szSql, -1)
        'Dim dt As DataTable = objHWSetting.selectForLHJByID(g_ws_lh, "1000T-19")
        DBacs.CommitTransaction()
        DataGridView1.DataSource = dtTa
    End Sub
    Public Sub connectDB()
        'イニシャルファイル情報取得
        g_szInitFileName = My.Application.Info.DirectoryPath & "\LHJServer.ini"

        g_Server.szDrive = GetIniFile("SERVER", "DRIVE", "PostgreSQL ANSI", g_szInitFileName)
        g_Server.szIPadr = GetIniFile("SERVER", "IP", "", g_szInitFileName)
        g_Server.szDbn = GetIniFile("SERVER", "DBN", "ZHENANSF", g_szInitFileName)
        g_Server.szUid = GetIniFile("SERVER", "UID", "sa", g_szInitFileName)
        g_Server.szPas = GetIniFile("SERVER", "PAS", "sa", g_szInitFileName)
        g_Server.iOver = CInt(GetIniFile("SERVER", "OVER", "-1", g_szInitFileName))

        '得到当前用户名
        g_LoginUser = GetIniFile("LOGIN", "user", "admin", g_szInitFileName)

        If False = g_fDBconnect And 0 = g_iDBconnResult Then
            If "" = g_Server.szIPadr Or "0.0.0.0" = g_Server.szIPadr Then
            Else
                g_fDBconnect = True

                'データベース接続
                With g_Server
                    g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    If 1 <> g_iDBconnResult Then
                        .szDrive = CStr(IIf("PostgreSQL" = .szDrive, "PostgreSQL ANSI", "PostgreSQL"))
                        g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    End If
                End With
            End If
        End If

        setAllErrMsg()
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Button1.PerformClick()
    End Sub

    Private Sub testForm_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not HslCommunication.Authorization.SetAuthorizationCode("e3e27344-1a9f-4d8b-b4fc-da5cae4b99bf") Then

        End If
        If Not HslControls.Authorization.SetAuthorizationCode("ce5ade06-6f14-4b0d-b9c2-0d625664dc3f") Then
        End If
        connectDB()
        'Label1.Text = Await test3()
        jxbPLC = New SiemensS7Net(SiemensPLCS.S1200)
        jxbPLC.IpAddress = "127.0.0.1"
        jxbPLC.Port = 102
        jxbPLC.SetPersistentConnection()
        'Timer1.Start()
    End Sub
    Private bbb As String

    Private jxbPLC As SiemensS7Net
    Private Function CurrentDomain_AssemblyResolve(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
        Dim dllName As String = If(args.Name.Contains(","), args.Name.Substring(0, args.Name.IndexOf(","c)), args.Name.Replace(".dll", ""))
        dllName = dllName.Replace(".", "_")
        If dllName.EndsWith("_resources") Then
            Return Nothing
        End If
        Dim rm As New System.Resources.ResourceManager([GetType].Namespace & ".Resources", System.Reflection.Assembly.GetExecutingAssembly())
        Dim bytes As Byte() = DirectCast(rm.GetObject(dllName), Byte())
        Return System.Reflection.Assembly.Load(bytes)
    End Function
    Public Sub New()
        AddHandler AppDomain.CurrentDomain.AssemblyResolve, New ResolveEventHandler(AddressOf CurrentDomain_AssemblyResolve)
        ' 此调用是设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。

    End Sub

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) 'Handles BackgroundWorker1.DoWork
        jxbPLC = New SiemensS7Net(SiemensPLCS.S1200)
        jxbPLC.IpAddress = "127.0.0.1"
        jxbPLC.Port = 102
        jxbPLC.SetPersistentConnection()
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)

        Dim a As OperateResult(Of TimeSpan) = jxbPLC.Wait("DB100.DBX1.0", True, 100, -1)
        If (worker.CancellationPending = True) Then
            Exit Sub
        End If
        'Dim bgw As BackgroundWorker = CType(sender, BackgroundWorker）
        'MsgBox(dtTa.Rows.Count())
        'While True
        '    Dim iii As Integer = test()
        '    bgw.ReportProgress(iii)
        '    bbb = iii
        '    If iii = "100" Then
        '        Exit While
        '    End If
        'End While
    End Sub
    'Function test() As Integer
    '    Dim aaa As String = GetIniFile("SERVER", "aaa", "", g_szInitFileName)
    '    If aaa <> "" OrElse a <> "0" Then
    '        Return CInt(aaa) * 10
    '    Else
    '        aaa = 0
    '    End If
    'End Function
    Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
        Label1.Text = e.ProgressPercentage
    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        Label1.Text = "完成"
        If e.Cancelled = True Then
            MsgBox("cancel  ")
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        BackgroundWorker1.RunWorkerAsync()
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

        'Label1.Text = "111"
        'Label1.Text = Await test3()
        BackgroundWorker2.CancelAsync()

    End Sub
    Private Async Function testbutton3async() As Task(Of String)
        Dim a As String = "121212"
        Dim tsk As Task(Of String) = test3()

        a = Await tsk
        Return a
    End Function
    Async Function test3() As Task(Of String)
        Await Task.Delay(10 * 1000)
        Return "DDDDDDDDDDDDDDD"
    End Function

    Public Async Sub ProcessRead()
        Dim filePath = "temp2.txt"

        If File.Exists(filePath) = False Then
            Debug.WriteLine("file not found: " & filePath)
        Else
            Try
                Dim text As String = Await ReadTextAsync(filePath)
                Debug.WriteLine(text)
            Catch ex As Exception
                Debug.WriteLine(ex.Message)
            End Try
        End If
    End Sub

    Private Async Function ReadTextAsync(filePath As String) As Task(Of String)

        Using sourceStream As New FileStream(filePath,
            FileMode.Open, FileAccess.Read, FileShare.Read,
            bufferSize:=4096, useAsync:=True)

            Dim sb As New StringBuilder

            Dim buffer As Byte() = New Byte(&H1000) {}
            Dim numRead As Integer
            numRead = Await sourceStream.ReadAsync(buffer, 0, buffer.Length)
            While numRead <> 0
                Dim text As String = Encoding.Unicode.GetString(buffer, 0, numRead)
                sb.Append(text)

                numRead = Await sourceStream.ReadAsync(buffer, 0, buffer.Length)
            End While

            Return sb.ToString
        End Using
    End Function

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click

        'MsgBox(getGYH_Header)
        Dim _BeginTime As DateTime = CDate("2022/08/21 01:00:00")

        MsgBox(Math.Abs(DateDiff(DateInterval.Minute, _BeginTime, Now)))
        MsgBox(Math.Abs(DateDiff(DateInterval.Minute, _BeginTime, Now)) / 60)
        MsgBox(Math.Floor(Math.Abs(DateDiff(DateInterval.Minute, _BeginTime, Now)) / 60))

    End Sub
    Public Function getGYH_Header() As String
        Dim ascYear As Integer = Asc("F")
        Dim gyhH As String = ""
        If Now.Year - 2021 + ascYear > 90 Then
            gyhH = "A"
        Else
            gyhH = Chr(Now.Year - 2021 + ascYear)
        End If
        Return "TS" & gyhH & "-"
    End Function

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        Dim dt As DateTime = "2021/11/18 9:1:4"
        MsgBox(dt.ToShortTimeString.ToString)
        'Dim objDB As New clsLHJWorkDetail
        'objDB.dataMoveToHistory(dtp1.Value)
        'MsgBox("OK")
    End Sub
    Enum LHJ_STATUS
        EMPTY = 0 '空闲
        BUSY = 1 '工作中
        LOSE_CONNECT = 2 '失联
        WAIT_OUT = 3 '等待出炉
        ERR = 4 '有错误
        REPAIRS = 5 '维修
    End Enum
    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        'MsgBox(LHJ_STATUS.WAIT_OUT)

        Dim speak As New SpeechSynthesizer
        'speak.SelectVoice("Microsoft Anna")
        speak.Volume = 100  '设置朗读音量 [范围 0 ~ 100]
        speak.Rate = NumericUpDown1.Value ' 设置朗读频率 [范围  -10 ~ 10]
        speak.SpeakAsync(TextBox1.Text)
        'speak.SpeakAsync("1000T-08        要出炉")
        'MsgBox("ok")
    End Sub

    Private Sub BackgroundWorker1_DoWork_1(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        jxbPLC = New SiemensS7Net(SiemensPLCS.S1200)
        jxbPLC.IpAddress = "127.0.0.1"
        jxbPLC.Port = 102
        jxbPLC.SetPersistentConnection()
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)

        Dim a As OperateResult(Of TimeSpan) = jxbPLC.Wait("DB100.DBX1.0", True, 100, -1)
        If (worker.CancellationPending = True) Then
            Exit Sub
        End If
    End Sub

    Private Sub BackgroundWorker2_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker2.DoWork

        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)

        'Dim a As OperateResult(Of TimeSpan) = 
        'If (worker.CancellationPending = True) Or jxbPLC.Wait("DB100.DBX1.0", True, 100, -1).IsSuccess Then
        '    Exit Sub
        'End If

        While jxbPLC.ReadBool("DB100.DBX1.0").Content = False And worker.CancellationPending = False
            Threading.Thread.Sleep(200)
        End While
        If worker.CancellationPending Then
            e.Cancel = True

        End If
        'For i As Integer = 0 To 100000
        '    i += 1
        'Next
    End Sub

    Private Sub BackgroundWorker2_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker2.RunWorkerCompleted
        Label1.Text = "完成"
        If e.Cancelled = True Then
            MsgBox("cancel  ")
        Else
            MsgBox("OK")
        End If
    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
        BackgroundWorker2.RunWorkerAsync()

    End Sub
End Class